<template>
    <div class="users-page">
      <!-- 搜索和筛选区域 -->
      <el-card shadow="never" class="search-card">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/邮箱/手机号"
              clearable
              style="width: 200px"
              @clear="handleSearch"
            />
          </el-form-item>
          
          <el-form-item label="角色">
            <el-select
              v-model="searchForm.role"
              placeholder="全部"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="顾客" value="customer" />
              <el-option label="商家" value="merchant" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="全部"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-statistic title="总用户数" :value="statistics.totalUsers || 0" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="顾客数量" :value="statistics.customerCount || 0" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="商家数量" :value="statistics.merchantCount || 0" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="活跃用户" :value="statistics.activeCount || 0" />
        </el-col>
      </el-row>
  
      <!-- 用户列表 -->
      <el-card shadow="never" class="table-card">
        <el-table
          v-loading="loading"
          :data="userList"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="用户信息" min-width="200">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :src="row.avatar" :size="40">
                  {{ row.username?.charAt(0)?.toUpperCase() }}
                </el-avatar>
                <div class="user-detail">
                  <div class="username">{{ row.username }}</div>
                  <div class="email">{{ row.email }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="realName" label="真实姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="130" />
          
          <el-table-column label="角色" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.role === 'customer'" type="primary">顾客</el-tag>
              <el-tag v-else-if="row.role === 'merchant'" type="success">商家</el-tag>
              <el-tag v-else type="warning">{{ row.role }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.status === 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="订单/消费" width="120">
            <template #default="{ row }">
              <div>订单：{{ row.orderCount || 0 }}</div>
              <div>消费：¥{{ row.totalSpent || '0.00' }}</div>
            </template>
          </el-table-column>
          
          <el-table-column prop="createdAt" label="注册时间" width="180" />
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.role !== 'admin'"
                :type="row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              
              <el-button
                v-if="row.role !== 'admin'"
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.totalItems"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Refresh } from '@element-plus/icons-vue'
  import { getUserList, updateUserStatus, deleteUser } from '@/api/users'
  
  const loading = ref(false)
  const userList = ref([])
  const statistics = ref({})
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    totalItems: 0,
    totalPages: 0
  })
  
  const searchForm = reactive({
    keyword: '',
    role: '',
    status: ''
  })
  
  // 加载用户列表
  const loadUserList = async () => {
    loading.value = true
    
    try {
      const params = {
        page: pagination.currentPage,
        size: pagination.pageSize,
        sortBy: 'createdAt',
        sortOrder: 'desc'
      }
      
      if (searchForm.keyword) params.keyword = searchForm.keyword
      if (searchForm.role) params.role = searchForm.role
      if (searchForm.status !== '') params.status = searchForm.status
      
      const res = await getUserList(params)
      
      userList.value = res.data.items
      statistics.value = res.data.statistics
      pagination.totalItems = res.data.pagination.totalItems
      pagination.totalPages = res.data.pagination.totalPages
    } catch (error) {
      console.error('加载用户列表失败：', error)
      ElMessage.error('加载用户列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    loadUserList()
  }
  
  // 重置
  const handleReset = () => {
    searchForm.keyword = ''
    searchForm.role = ''
    searchForm.status = ''
    pagination.currentPage = 1
    loadUserList()
  }
  
  // 切换用户状态
  const handleToggleStatus = (row) => {
    const newStatus = row.status === 1 ? 0 : 1
    const action = newStatus === 0 ? '禁用' : '启用'
    
    ElMessageBox.confirm(`确定要${action}用户 ${row.username} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await updateUserStatus(row.id, newStatus)
        ElMessage.success(`${action}成功`)
        loadUserList()
      } catch (error) {
        console.error(`${action}用户失败：`, error)
        ElMessage.error(`${action}失败`)
      }
    }).catch(() => {})
  }
  
  // 删除用户
  const handleDelete = (row) => {
    ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？删除后数据将无法恢复！`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    ).then(async () => {
      try {
        await deleteUser(row.id)
        ElMessage.success('删除成功')
        loadUserList()
      } catch (error) {
        console.error('删除用户失败：', error)
        ElMessage.error(error.message || '删除失败')
      }
    }).catch(() => {})
  }
  
  // 分页大小改变
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadUserList()
  }
  
  // 当前页改变
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    loadUserList()
  }
  
  onMounted(() => {
    loadUserList()
  })
  </script>
  
  <style scoped>
  .users-page {
    width: 100%;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .user-detail {
    flex: 1;
  }
  
  .username {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .email {
    font-size: 12px;
    color: #909399;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>
